import Coordinates from "../Coordinates";
import IconFramesMgr from "../IconFramesMgr";
import LevelLogic from "../logic/LevelLogic";
import NativeCaller from "../NativeCaller";
import PlayerDataMgr from "../PlayerDataMgr";
import ResManager from "../ResManager";
import Util from "../../../StartAb/Util";
import TurnTableSystem from "../system/TurnTableSystem";
import CoinSystem from "../system/CoinSystem";
import GardenSystem from "../garden/GardenSystem";
import WXAD from "../../../StartAb/WXAd";
import WXUtil from "../../../StartAb/WXUtil";
import ResLoading from "../../../StartAb/ResLoading";
import ResLoadingAdapter from "../../../StartAb/ResLoadingAdapter";
import WXRealLogUtil from "../../../StartAb/WXRealLogUtil";

const { ccclass, property } = cc._decorator;

@ccclass
export default class HomeScene extends cc.Component {

    @property(cc.Node)
    levelListNode: cc.Node = null;
    @property(cc.Node)
    nextLevelNode: cc.Node = null;

    @property(cc.Label)
    levelText: cc.Label = null;

    //下一关的图片，如果是去关卡列表呢？就先显示最后一关的图标吧
    @property(cc.Sprite)
    levelSprite: cc.Sprite = null;

    currentPlayLevel = 0

    //true 表示直接开始下一关，false表示进到关卡列表
    isHasNextLevel = false;

    onLoad() {
        PlayerDataMgr.getInstance().loadDataFromPersistence();
        TurnTableSystem.load();
        CoinSystem.load();
        GardenSystem.load();
        window['allpass'] = HomeScene.makeLevelAll3Star
    }

    protected onDisable(): void {
        WXAD.instance.hideBannerCell()
    }

    start() {
        WXAD.instance.hideBanner();
        WXAD.instance.showBannerCell();
        this.currentPlayLevel = LevelLogic.getCurrentPlayLevel();
        this.isHasNextLevel = (this.currentPlayLevel < ResManager.getLevelResArray().length && (this.currentPlayLevel >= 0));
        this.levelListNode.active = LevelLogic.isAllLevelDone();
        this.nextLevelNode.active = !LevelLogic.isAllLevelDone();
        if (LevelLogic.isAllLevelDone() == false) {
            // WXUtil.retryCall(this._loadAndGoToNext, this, "提示", "资源加载失败, 需要重试")
            this._loadLevelPic()
        }
        WXRealLogUtil.info("进入首页,当前关卡:" + this.currentPlayLevel);
    }

    _loadLevelPic() {
        this.levelText.string = (this.currentPlayLevel + 1).toString();
        let frameName = ResManager.getLevelResNameByIndex(this.currentPlayLevel);
        ResLoadingAdapter.show({
            title: '加载资源'
        })
        let self = this
        // WXRealLogUtil.info("首页加载关卡图片开始:" + frameName);
        cc.assetManager.loadBundle("LevelAb", (err: Error, b: cc.AssetManager.Bundle) => {
            if (err) {
                ResLoadingAdapter.hide()
                WXUtil.retryCall(self._loadLevelPic, self, "提示", "资源加载失败, 需要重试")
                WXRealLogUtil.error("加载关卡图片出错:" + err.message);
                return console.error(err.message);
            }
            console.log("LevelAb load完成");
            b.load(frameName, cc.SpriteFrame, (err: Error, sf: cc.SpriteFrame) => {
                ResLoadingAdapter.hide()
                if (err) {
                    WXUtil.retryCall(self._loadLevelPic, self, "提示", "资源加载失败, 需要重试")
                    WXRealLogUtil.error("加载关卡图片出错:" + err.message);
                    return console.error(err.message);
                }
                WXRealLogUtil.info("首页加载关卡图片完成:" + frameName);
                if (self.isValid)
                    self.levelSprite.spriteFrame = sf;
            })
        })
    }

    play(e: cc.Event.EventTouch) {
        let btn: cc.Button = e.target.getComponent(cc.Button);
        btn && (btn.enabled = false)
        ResLoadingAdapter.show({
            title: '准备开始'
        })
        // WXRealLogUtil.info("点击了开始,加载坐标配置:" + this.currentPlayLevel);
        Coordinates.loadLvCoordinate(this.currentPlayLevel, () => {
            ResManager.currentLevelIndex = this.currentPlayLevel
            PlayerDataMgr.getInstance().setLastLevelIndex(this.currentPlayLevel)
            cc.director.preloadScene("game", null, (err: Error) => {
                if (err)
                    WXRealLogUtil.error("预加载game场景失败:" + err.message);
                ResLoadingAdapter.hide()
                WXAD.instance.hideBanner();
                Util.changeScene("game");
            })
        })
    }

    levelList(e: cc.Event.EventTouch) {
        let btn: cc.Button = e.target.getComponent(cc.Button);
        btn && (btn.interactable = false)
        ResLoadingAdapter.show({
            title: '加载关卡图标'
        })
        WXRealLogUtil.info("加载关卡图标开始");
        IconFramesMgr.getInstance().loadIcons(() => {
            WXRealLogUtil.info("加载关卡图标完成");
            ResLoadingAdapter.hide()
            Util.changeScene("levelList");
        })

    }


    _loadOpenTurn() {
        ResLoadingAdapter.show({
            title: ''
        })
        let self = this
        WXRealLogUtil.info("加载转盘资源开始");
        cc.assetManager.loadBundle("turntable", (err, bundle) => {
            if (err) {
                ResLoadingAdapter.hide()
                WXUtil.retryCall(self._loadOpenTurn, self, "提示", "资源加载失败, 需要重试")
                WXRealLogUtil.error("加载转盘资源出错:" + err.message);
                return console.error(err.message)
            }
            bundle.load("turntable", cc.Prefab, ((err: Error, pf: cc.Prefab) => {
                ResLoadingAdapter.hide()
                if (err) {
                    WXUtil.retryCall(self._loadOpenTurn, self, "提示", "资源加载失败, 需要重试")
                    WXRealLogUtil.error("加载转盘资源出错:" + err.message);
                    return console.log(err.message);
                }
                WXRealLogUtil.info("加载转盘资源完成");
                WXAD.instance.hideBannerCell()
                let dialog = cc.instantiate(pf);
                if (self.isValid)
                    dialog.parent = self.node;
            }))
        })
    }

    openTurn(e: cc.Event.EventTouch) {
        // let btn: cc.Button = e.target.getComponent(cc.Button);
        // WXUtil.retryCall(this._loadOpenTurn, this, "提示", "资源加载失败, 需要重试")

        this._loadOpenTurn()
    }

    openDailyTask(e: cc.Event.EventTouch) {
        WXAD.instance.hideBannerCell()
        let btn: cc.Button = e.target.getComponent(cc.Button);
        btn.interactable = false;
        WXRealLogUtil.info("加载每日任务资源开始");
        cc.assetManager.getBundle("GameAb").load("prefab/DailyTaskRoot", cc.Prefab, ((err: Error, pf: cc.Prefab) => {
            btn.interactable = true;
            if (err) {
                WXRealLogUtil.error("加载每日任务资源出错:" + err.message);
                return console.log(err.message);
            }
            WXRealLogUtil.info("加载每日任务资源完成");
            let dialog = cc.instantiate(pf);
            if (this.isValid)
                dialog.parent = this.node;
        }))
    }

    static makeLevelAll3Star() {
        for (let i = 0; i < ResManager.levelResArray.length; ++i) {
            PlayerDataMgr.getInstance().updateLevelStar(i, 3)
        }
        console.log("IAD all level locked")
    }
}
